﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MailS;

public partial class Move_Rep_Submit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string condition = "";
        string pronum = Session["pro_num"].ToString();

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringProManage"].ConnectionString;
        try
        {
            conn.Open();
            //读仪器名称
            string SQLc = "select condition from Products where pro_num=@pronum";
            SqlCommand cmdc = new SqlCommand();
            cmdc.Connection = conn;
            cmdc.CommandType = CommandType.Text;
            cmdc.CommandText = SQLc;
            SqlParameter p1 = new SqlParameter("@pronum", pronum);
            cmdc.Parameters.Add(p1);
            //cmdimg.ExecuteNonQuery();
            condition = cmdc.ExecuteScalar().ToString();
            if (condition == "正在维修")
            {
                BtSubmit.Enabled = true;
            }
            else
            {
                BtSubmit.Enabled = false;
            }

            string tabelrep = "<table class='layui-table'><thead> <tr><td colspan='8' style='background-color: #EEE;font-size:large;text-align:center'>该设备的报修维修记录</td></tr><tr><th>报修时间</th><th>报修原因</th><th>维修时间</th><th>维修过程</th></tr></thead>";
            string SQLrep = "select date_inform,rep_cause,date_rep,rep_program from Repair where (pro_num=@pronum and flag=1)";
            SqlCommand cmdrep = new SqlCommand();
            cmdrep.Connection = conn;
            cmdrep.CommandType = CommandType.Text;
            cmdrep.CommandText = SQLrep;
            SqlParameter p4 = new SqlParameter("@pronum", pronum);
            cmdrep.Parameters.Add(p4);
            using (SqlDataReader readerrep = cmdrep.ExecuteReader())
            {
                int fieldcount = readerrep.FieldCount;      //取字段总数
                if (!readerrep.HasRows)            //有数据  ---行
                {
                    LabelRepair.Text = "<table class='layui-table' style='width: 70%; margin-left:15% '><tr><td>此仪器没有报修维修记录</td></tr>";
                }
                else
                {
                    string trd = "<tbody>";                     //存储数据
                    while (readerrep.Read())               //当有数据可读时
                    {
                        trd += "<tr>";         //数据行开始，行以tr起
                        for (int i = 0; i < fieldcount; i++)
                        {   //每一列的内容
                            trd += "<td>" + readerrep[i].ToString() + "</td>";
                        }
                        //行结束
                    }

                    LabelRepair.Text = tabelrep + trd + "</tbody></table>";
                }
            }
        }
        finally
        {
            conn.Close();
        }
    }

    protected void BtSubmit_Click(object sender, EventArgs e)
    {
        string date0 = DateTime.Now.ToString("yyyy-MM-dd");
        string time = DateTime.Now.ToLongTimeString().ToString();
        string date = date0 + " " + time;
        string program = FRepair.Text;
        string pronum = Session["pro_num"].ToString();
        string UserId=Session["Move_Name"].ToString();
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringProManage"].ConnectionString;
        try
        {
            conn.Open();
            string SQL = "update Repair set date_rep=@date_rep,rep_program=@rep_program,rep_perId=@rep_perId,condition=N'维修完成' where (pro_num=@pro_num and flag=1 and condition=N'正在维修')";
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = SQL;
            SqlParameter pdate = new SqlParameter("@date_rep", SqlDbType.NVarChar, 20);
            pdate.Value = date;
            cmd.Parameters.Add(pdate);

            SqlParameter pprogram = new SqlParameter("@rep_program", SqlDbType.NVarChar, 100);
            pprogram.Value = program;
            cmd.Parameters.Add(pprogram);

            SqlParameter pUserId = new SqlParameter("@rep_perId", SqlDbType.NVarChar, 10);
            pUserId.Value = UserId;
            cmd.Parameters.Add(pUserId);

            SqlParameter ppronum = new SqlParameter("@pro_num", SqlDbType.NVarChar, 10);
            ppronum.Value = pronum;
            cmd.Parameters.Add(ppronum);

            int R = cmd.ExecuteNonQuery();  //R 的值就是返回影响表的行数
            if (R > 0)
            {
                Session["Message"] = "更新维修记录成功，辛苦啦！";
                //设备状态和报修记录状态修改
                string SQLcon = "update Products set condition=N'正常' where (pro_num=@proid) and (flag=1)";
                SqlCommand cmdcon = new SqlCommand();
                cmdcon.Connection = conn;
                cmdcon.CommandType = CommandType.Text;
                cmdcon.CommandText = SQLcon;
                SqlParameter ppro_num = new SqlParameter("@proid", SqlDbType.NVarChar, 10);
                ppro_num.Value = pronum;
                cmdcon.Parameters.Add(ppro_num);
                cmdcon.ExecuteNonQuery();

                string SqlGetBookingTime = "select book_id,phone_num,date,time from booking where condition=N'预约成功' and flag=1 and pro_num=@pro_num";
                string BookingTime = "";          //数据库读取的时间段
                string SubBookingTime = "";       //数据库读取的时间取起始时间
                string BookingDate = "";          //数据库读取的日期
                string BookingDateSum = "";       //数据库读取的日期加起始时间
                string BookingTimeSpan = "";      //数据库读取的时间加时间段（放在邮件里的）
                DateTime ConvertBookingDateSum = new DateTime();
                string Phone_Num = "";
                string useremail = "";
                string username = "";
                //string userdevicenum = "";
                string title = "";
                string body = "";
                SqlCommand CmdGetBookingTime = new SqlCommand();
                CmdGetBookingTime.Connection = conn;
                CmdGetBookingTime.CommandType = CommandType.Text;
                CmdGetBookingTime.CommandText = SqlGetBookingTime;
                SqlParameter pppro_num = new SqlParameter("@pro_num", SqlDbType.NVarChar, 10);
                pppro_num.Value = pronum;
                CmdGetBookingTime.Parameters.Add(pppro_num);
                using (SqlDataReader reader = CmdGetBookingTime.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Phone_Num += reader["phone_num"].ToString() + "|";
                        BookingDate = reader["date"].ToString();
                        BookingTime = reader["time"].ToString();
                        SubBookingTime = BookingTime.Substring(0, 5);
                        BookingTimeSpan += BookingDate + " " + BookingTime + "|";
                        BookingDateSum += BookingDate + " " + SubBookingTime + "|";
                        //BookingIdSum += reader["book_id"].ToString() + "|";
                    }
                }
                string[] SinglePhone_NUM = Phone_Num.Split('|');
                string[] SingleBookingDateSum = BookingDateSum.Split('|');
                string[] SingleBookingTimeSpan = BookingTimeSpan.Split('|');
                for (int i = 0; i < SinglePhone_NUM.Length - 1; i++)
                {
                    ConvertBookingDateSum = System.Convert.ToDateTime(SingleBookingDateSum[i]);
                    if (ConvertBookingDateSum >= DateTime.Now)
                    {
                        string Sqlgetusermail = "select name,email from users where tel=@usertel and flag=1";
                        SqlCommand sqlcmdgetusermail = new SqlCommand();
                        sqlcmdgetusermail.Connection = conn;
                        sqlcmdgetusermail.CommandText = Sqlgetusermail;
                        sqlcmdgetusermail.CommandType = CommandType.Text;
                        SqlParameter pusertel = new SqlParameter("@usertel", SqlDbType.VarChar, 11);
                        pusertel.Value = SinglePhone_NUM[i];
                        sqlcmdgetusermail.Parameters.Add(pusertel);
                        using (SqlDataReader reader1 = sqlcmdgetusermail.ExecuteReader())
                        {
                            while (reader1.Read())
                            {
                                useremail = reader1["email"].ToString();
                                username = reader1["name"].ToString();
                                title = "[设备维修提醒]";
                                body = "尊敬的 " + username + " 先生/女士，由于您预约的编号为 " + pronum + " 的设备已修好，您可以在您的原定预约时间(" + SingleBookingTimeSpan[i] + ")内使用该设备，特此通知！";
                                EmailS.SendingMail(useremail, title, body);

                            }
                        }

                        //string SqlUpdateFlag = "update Booking set flag=0 where book_id=@book_id";
                        //SqlCommand SqlCmdUpdateFlag = new SqlCommand();
                        //SqlCmdUpdateFlag.Connection = conn;
                        //SqlCmdUpdateFlag.CommandType = CommandType.Text;
                        //SqlCmdUpdateFlag.CommandText = SqlUpdateFlag;
                        //SqlParameter pbook_id = new SqlParameter("@book_id", SqlDbType.Int);
                        //pbook_id.Value = Convert.ToInt32(SingleBookingIdSum[i]);
                        //SqlCmdUpdateFlag.Parameters.Add(pbook_id);
                        //SqlCmdUpdateFlag.ExecuteNonQuery();


                    }

                }




                Session["ReturnPath"] = "Move_Rep_Submit.aspx";
                Response.Redirect("Success.aspx");
            }
            else
            {
                Session["Message"] = "更新维修记录失败";
                Response.Redirect("Error.aspx");
            }

            //更改仪器状态
            
        }
        finally
        {
            conn.Close();
        }

    }
}